﻿using System;
using System.Xml.Linq;
using System.Xml.XPath;
using TestTracking.Interface;

namespace TestTracking.Helper
{
    public class XmlHelp : IXmlHelp
    {
        private XDocument xdoc = null;

        public XmlHelp(string path)
        {
            if (path == "")
            {
                _path = System.IO.Path.Combine(Environment.CurrentDirectory, "ApplicationConfig.xml"); //默认路径
            }
            else
            {
                _path = path;
            }
            xdoc = XDocument.Load(_path);
        }

        private string _path; //xml文件保存路径

        public string Path
        {
            get
            {
                return _path;
            }
            private set
            {
                _path = value;
            }
        }

        /// <summary>
        /// 读取节点的值
        /// </summary>
        /// <typeparam name="T">返回的类型</typeparam>
        /// <param name="xpath">xml路径</param>
        /// <returns></returns>
        public T GetNoteValue<T>(string xpath)
        {
            XElement rootElement = xdoc?.Root;
            XElement targetElement = rootElement.XPathSelectElement(xpath);
            return (T)Convert.ChangeType(targetElement.Value, typeof(T));
        }
        /// <summary>
        /// 获取节点元素
        /// </summary>
        /// <param name="xpath">xml路径</param>
        /// <returns></returns>
        public XElement GetElement(string xpath)
        {
            XElement rootElement = xdoc.Root;
            XElement targetElement = rootElement.XPathSelectElement(xpath);
            return targetElement;
        }
        public void Save()
        {
            xdoc?.Save(System.IO.Path.Combine(Environment.CurrentDirectory, "ApplicationConfig.xml"));
        }
    }
}